<?php
class JqgridDataHandle extends AbsDataHandle {
	private static $options = array(
		'records' => 100,
		'page' => 1,
		'perpage' => 10,
	);
	
	public static function getType() {
		return 'jqgrid';
	}
	
	public static function handle($defineCfg) {
		$options = (isset($defineCfg['options']) && is_array($defineCfg['options'])) ? $defineCfg['options'] : array();
		
		$options = array_merge(self::$options, $options);
		
		return self::genData($options);
	}
	
	private static function genData($options) {
		$data = array();
		# total records
		$data['records'] = $options['records'];
		# current page
		$data['page'] = $options['page'];
		# total page
		$data['total'] = ceil($options['records'] / $options['perpage']);
		
		$data['page'] = max($data['page'], 1);
		$data['page'] = min($data['page'], $data['total']);
		
		$fields = (isset($options['fields']) && is_array($options['fields'])) ? $options['fields'] : array();
		# record number show in current page
		$itemNum = $data['records'] - ($data['page'] - 1) * $options['perpage'];
		$itemNum = min($itemNum, $options['perpage']);
		$data['rows'] = array();
		for($i = 1; $i <= $itemNum; ++$i) {
			$item = array(
				'id' => $i,
			);
			$cell = array();
			$search = $replace = array();
			$incrementSet = false;
			foreach($fields as $field => $type) {
				$typeClz = ucfirst(strtolower($type)) . 'DataHandle';
				if(class_exists($typeClz)) {
					$defineCfg = array(
						'type' => $type,
					);
					
					if(isset($options["field_{$field}"])) {
						$defineCfg['options'] = $options["field_{$field}"];
					}
					$rowData = DCenter::data($defineCfg, DCenter::getCfg());
					$search[] = '{' . strtoupper($field) . '}';
					$replace[] = $rowData;
					if(IncrementDataHandle::getType() === strtolower($type) && !$incrementSet) {
						$item['id'] = $rowData;
						$incrementSet = true;
					}
				} else {
					$rowData = $type;
				}
				
				$cell[$type] = $rowData;
			}
			$item['cell'] = self::handleReplace($search, $replace, $cell);
			$data['rows'][] = $item;
		}
		
		return $data;
	}
	
	private static function handleReplace($search, $replace, $cell) {
		$ret = array();
		foreach($cell as $type => $val) {
			$typeClz = ucfirst(strtolower($type)) . 'DataHandle';
			if(class_exists($typeClz)) {
				$ret[] = $val;
			} else {
				$ret[] = str_replace($search, $replace, $val);
			}
		}
		
		return $ret;
	}
}
?>